package com.woniu.tms.manage.service.impl;

import com.github.pagehelper.PageHelper;
import com.woniu.tms.entity.*;
import com.woniu.tms.manage.service.LogService;
import com.woniu.tms.mapper.LogformMapper;
import com.woniu.tms.mapper.RoleMapper;
import com.woniu.tms.mapper.UserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class LogServiceImpl implements LogService {

    @Autowired
    LogformMapper logformMapper;
    @Autowired
    UserRoleMapper userRoleMapper;
    @Autowired
    RoleMapper roleMapper;

    @Override
    public List<Logform> list(String condition, String rname, Integer pageNum, Integer pageSize) {
        // 根据uid查出角色的操作记录
        LogformExample logformExample = new LogformExample();
        LogformExample.Criteria criteria = logformExample.createCriteria();
        if (!"角色".equals(rname)) {
            RoleExample roleExample = new RoleExample();
            roleExample.createCriteria().andRnameEqualTo(rname);
            List<Role> roleList = roleMapper.selectByExample(roleExample);
            // 查出rid对应所有角色的uid
            UserRoleExample userRoleExample = new UserRoleExample();
            userRoleExample.createCriteria().andRidEqualTo(roleList.get(0).getRid());
            List<UserRole> userRoleList = userRoleMapper.selectByExample(userRoleExample);
            if (userRoleList.size() != 0) {
                List<Integer> list = new ArrayList<>();
                for (UserRole userRole : userRoleList) {
                    list.add(userRole.getUid());
                }
                criteria.andUidIn(list);
            } else {
                return new ArrayList<Logform>();
            }
        }
        criteria.andInfoLike("%" + condition + "%");
        PageHelper.startPage(pageNum, pageSize);
        return logformMapper.selectByExample(logformExample);
    }
}
